/**
=========================================================
* Material Dashboard 2 React - v2.2.0
=========================================================

* Product Page: https://www.creative-tim.com/product/material-dashboard-react
* Copyright 2023 Creative Tim (https://www.creative-tim.com)

Coded by www.creative-tim.com

 =========================================================

* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*/

// @mui material components
import Grid from "@mui/material/Grid";
import Card from "@mui/material/Card";

// Material Dashboard 2 React components
import MDBox from "components/MDBox";
import MDTypography from "components/MDTypography";

// Material Dashboard 2 React example components
import DashboardLayout from "examples/LayoutContainers/DashboardLayout";
import DashboardNavbar from "examples/Navbars/DashboardNavbar";
import Footer from "examples/Footer";
import DataTable from "examples/Tables/DataTable";

// Data
import authorsTableData from "layouts/tables/data/authorsTableData";
import projectsTableData from "layouts/tables/data/projectsTableData";
import axios from "axios";
import { useEffect, useState } from "react";
import MDButton from "../../components/MDButton";

function Tables() {
  const [userData, setUserData] = useState([]);

  const [loading, setLoading] = useState(null); // 记录哪个商品正在收藏
  const [favorites, setFavorites] = useState({}); // 记录收藏状态

  // 使用 useEffect 获取数据
  useEffect(() => {
    const token = localStorage.getItem("authToken");
    const fetchData = async () => {
      try {
        const response = await axios.get("http://localhost:8848/warehouse/numberOfComments", {
          headers: {
            Authorization: `Bearer ${token}`, // 添加 Bearer 前缀
          },
          withCredentials: true,
        });
        console.log("Response data:", response.data);
        console.log("User data:", response.data);
        if (response.data) {
          setUserData(response.data);
        } else {
          console.error("User data is not available.");
        }
        await axios.post(
          "http://localhost:8848/addLog",
          {
            operate: "查看了热门商品",
          },
          {
            headers: { Authorization: `Bearer ${token}` }, // 发送请求时携带 Token
            withCredentials: true,
          }
        );
        /*alert(response.data.data.id);*/
      } catch (error) {
        console.error("获取数据失败:", error);
      }
    };

    fetchData();
  }, []);

  const handleFavorite = async (item) => {
    setLoading(item.name);
    try {
      const token = localStorage.getItem("authToken"); // 获取 Token
      const response = await axios.post(
        "http://localhost:8848/shouCang/addShouCang",
        { name: item.name, price: item.price, image: item.image, tableId: item.id },
        {
          headers: { Authorization: `Bearer ${token}` }, // 发送请求时携带 Token
          withCredentials: true,
        }
      );

      if (response.status === 200) {
        setFavorites((prev) => ({ ...prev, [item.name]: true })); // 更新收藏状态
      }
    } catch (error) {
      console.error("收藏失败:", error);
    } finally {
      setLoading(null);
    }
  };

  useEffect(() => {
    console.log("Updated userData:", userData); // 在 userData 更新时查看数据
    console.log(userData.username);
    console.log(userData.length);
  }, [userData]);

  return (
    <DashboardLayout>
      <DashboardNavbar />
      {/*主界面*/}
      <MDBox py={3}>
        <Grid container spacing={3}>
          {userData.map((item, index) => (
            <Grid xs={12} sm={6} md={4} key={index}>
              <MDBox
                display="flex"
                flexDirection="column"
                alignItems="center"
                p={2}
                borderRadius={2}
                shadow={2}
              >
                <img src={item.image} alt="商品图片" style={{ width: "250px", height: "250px" }} />
                <MDTypography variant="h5" gutterBottom>
                  {item.name}
                </MDTypography>
                <MDTypography variant="body2" color="textSecondary">
                  销量: {item.number}
                </MDTypography>
                <MDTypography variant="body1" color="primary">
                  价格: {item.price}
                </MDTypography>
                <MDTypography variant="body2" color="primary">
                  {item.param_info}
                </MDTypography>
                <MDTypography variant="body2" color="textSecondary">
                  <a href={item.href} target="_blank" rel="noopener noreferrer">
                    查看详情
                  </a>
                </MDTypography>
                <MDButton
                  variant="contained"
                  color={favorites[item.name] ? "success" : "primary"}
                  onClick={() => handleFavorite(item)}
                  disabled={loading === item.name} // 仅在当前点击的商品上显示加载状态
                >
                  {favorites[item.name] ? "已收藏" : "收藏"}
                </MDButton>
              </MDBox>
            </Grid>
          ))}
        </Grid>
      </MDBox>
      {/*<Footer />*/}
    </DashboardLayout>
  );
}
export default Tables;

/*const { columns, rows } = authorsTableData();
  const { columns: pColumns, rows: pRows } = projectsTableData();

  return (
    <DashboardLayout>
      <DashboardNavbar />
      <MDBox pt={6} pb={3}>
        <Grid container spacing={6}>
          <Grid item xs={12}>
            <Card>
              <MDBox
                mx={2}
                mt={-3}
                py={3}
                px={2}
                variant="gradient"
                bgColor="info"
                borderRadius="lg"
                coloredShadow="info"
              >
                <MDTypography variant="h6" color="white">
                  Authors Table
                </MDTypography>
              </MDBox>
              <MDBox pt={3}>
                <DataTable
                  table={{ columns, rows }}
                  isSorted={false}
                  entriesPerPage={false}
                  showTotalEntries={false}
                  noEndBorder
                />
              </MDBox>
            </Card>
          </Grid>
          <Grid item xs={12}>
            <Card>
              <MDBox
                mx={2}
                mt={-3}
                py={3}
                px={2}
                variant="gradient"
                bgColor="info"
                borderRadius="lg"
                coloredShadow="info"
              >
                <MDTypography variant="h6" color="white">
                  Projects Table
                </MDTypography>
              </MDBox>
              <MDBox pt={3}>
                <DataTable
                  table={{ columns: pColumns, rows: pRows }}
                  isSorted={false}
                  entriesPerPage={false}
                  showTotalEntries={false}
                  noEndBorder
                />
              </MDBox>
            </Card>
          </Grid>
        </Grid>
      </MDBox>
      <Footer />
    </DashboardLayout>
  );
}
*/
